package com.settlement.system.controller;

import com.settlement.system.common.result.Result;
import com.settlement.system.model.vo.SmsVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/v1/sms")
@RequiredArgsConstructor
public class SmsController {

    private final static Logger logger = LoggerFactory.getLogger(SmsController.class);

    private static final ConcurrentHashMap<String, String> SMS_CODE_MAP = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, LocalDateTime> SMS_CODE_TIME_MAP = new ConcurrentHashMap<>();

    @Operation(summary = "通过手机号码获取短信内容")
    @GetMapping("/info/{phone}")
    public Result<String> info(@Parameter(description = "手机号码") @PathVariable String phone) {
        String text = SMS_CODE_MAP.get(phone);
        logger.info("获取手机号码：{}，短信内容：{}", phone, text);
        // 删除5分钟之后的数据
        List<String> expiredKeys = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (String phoneNumber : SMS_CODE_TIME_MAP.keySet()) {
            if (Math.abs(Duration.between(now, SMS_CODE_TIME_MAP.get(phoneNumber)).toMinutes()) > 5) {
                expiredKeys.add(phoneNumber);
            }
        }
        if (expiredKeys.size() > 0) {
            for (String expiredKey : expiredKeys) {
                SMS_CODE_MAP.remove(expiredKey);
                SMS_CODE_TIME_MAP.remove(expiredKey);
            }
        }
        return Result.success(text);
    }

    @Operation(summary = "保存手机号码获取短信内容")
    @PostMapping("/save")
    public Result<String> save(@RequestBody @Valid SmsVo smsVo) {
        logger.info("保存手机号码：{}，短信内容：{}", smsVo.getPhone(), smsVo.getText());
        SMS_CODE_MAP.put(smsVo.getPhone(), smsVo.getText());
        SMS_CODE_TIME_MAP.put(smsVo.getPhone(), LocalDateTime.now());
        // 删除5分钟之后的数据
        List<String> expiredKeys = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (String phone : SMS_CODE_TIME_MAP.keySet()) {
            if (Math.abs(Duration.between(now, SMS_CODE_TIME_MAP.get(phone)).toMinutes()) > 5) {
                expiredKeys.add(phone);
            }
        }
        if (expiredKeys.size() > 0) {
            for (String expiredKey : expiredKeys) {
                SMS_CODE_MAP.remove(expiredKey);
                SMS_CODE_TIME_MAP.remove(expiredKey);
            }
        }
        return Result.success();
    }
}
